package com.tchintech.pay.view.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tchintech.pay.R;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.net.OkhttpClientTest;
import com.tchintech.pay.utils.AppConst;
import com.tchintech.pay.utils.TimeUtil;
import com.tchintech.pay.utils.keyboard.VirtualKeyboardView;
import com.tchintech.pay.utils.zxing.android.CaptureActivity;
import com.tchintech.pay.view.fragment.MainFragment;
import com.tchintech.pay.widget.DialogWiget;

import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/12 0012.
 * <p>
 * <p>
 * <p>
 * 银行卡快捷支付界面
 */

public class QuickPayActivity extends Activity implements View.OnClickListener {
    private String cardUrl = "FastPayment.quick";
    private String isenter_url = "MerchantsReported.isenter";
    private String code_url = "Code.code";

    private static final int REQUEST_CODE_SCAN = 1575;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private Map<String, String> map;
    private VirtualKeyboardView virtualKeyboardView;
    private GridView gridView;
    private ArrayList<Map<String, String>> valueList;

    private EditText textAmount;

    private Animation enterAnim;

    private Animation exitAnim;
    private PopupWindow mPopWindow;
    private RelativeLayout real_sao, real_code, real_q1, real_q2;
    private LinearLayout line_bk;

    private TextView tv_title;
    private ImageView iv_back;

    private int pay_type = 0;
    private String money = "0";
    private Handler handler;
    public ProgressDialog pd;
    private Intent intent = new Intent();
    private String channel_name = "";

    private String busCode = "";
    //二维码扫描结果
    private String authCode = "";

    private DialogWiget dialog = new DialogWiget();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_normal_key_board);
        initAnim();
        initView();
        valueList = virtualKeyboardView.getValueList();
        handler();
        backgroundAlpha(1f);
        //仅在此保存当前activity便于在二维码界面关闭此界面
        MainFragment.listA.add(this);
    }

    /**
     * 数字键盘显示动画
     */
    private void initAnim() {

        enterAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_in);
        exitAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_out);
    }

    //显示遮罩
    public void showProgressDialog(String title, String text) {
        pd = ProgressDialog.show(this, title, text);
    }


    private void initView() {

        textAmount = (EditText) findViewById(R.id.textAmount);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("快捷支付");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        // 设置不调用系统键盘
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            textAmount.setInputType(InputType.TYPE_NULL);
        } else {
            this.getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus",
                        boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(textAmount, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        virtualKeyboardView = (VirtualKeyboardView) findViewById(R.id.virtualKeyboardView);
        virtualKeyboardView.getLayoutBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                virtualKeyboardView.startAnimation(exitAnim);
                virtualKeyboardView.setVisibility(View.GONE);
            }
        });

        gridView = virtualKeyboardView.getGridView();
        gridView.setOnItemClickListener(onItemClickListener);

        textAmount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                virtualKeyboardView.setFocusable(true);
                virtualKeyboardView.setFocusableInTouchMode(true);

                virtualKeyboardView.startAnimation(enterAnim);
                virtualKeyboardView.setVisibility(View.VISIBLE);
            }
        });

    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            if (position > 2 && position < 14 && position != 12) {    //点击0~9按钮

                String amount = textAmount.getText().toString().trim();
                amount = amount + valueList.get(position).get("name");

                textAmount.setText(amount);

                Editable ea = textAmount.getText();
                textAmount.setSelection(ea.length());
            } else {
                if (position == 12) {      //点击退格键
                    String amount = textAmount.getText().toString().trim();
                    if (!amount.contains(".")) {
                        amount = amount + valueList.get(position).get("name");
                        textAmount.setText(amount);

                        Editable ea = textAmount.getText();
                        textAmount.setSelection(ea.length());
                    }
                }

                if (position == 14) {      //点击退格键
                    String amount = textAmount.getText().toString().trim();
                    if (amount.length() > 0) {
                        amount = amount.substring(0, amount.length() - 1);
                        textAmount.setText(amount);

                        Editable ea = textAmount.getText();
                        textAmount.setSelection(ea.length());
                    }
                }
                if (position == 0) {
                    isEnter();
                    pay_type = 1;
                }
                if (position == 1) {
                    isEnter();
                    pay_type = 2;
                }
                if (position == 2) {
                    //交易时段为早上8点到晚上10点
                    if (!TimeUtil.isDeal()) {
                        dialog.showMessage(QuickPayActivity.this, "无法交易", "交易时段为每天08:00~22:00");
                        return;
                    }
                    //银联   跳转新界面
                    money = textAmount.getText().toString().trim();
                    if (money.equals("")) {
                        money = "0";
                    }
                    double mf = Double.parseDouble(money);
                    if (mf >= 100.00) {
                        pay_type = 3;
                        showPopupWindow(pay_type, "#1C5993");
                    } else {
                        showMsg("支付金额不能小于100");
                    }

                }
            }
        }
    };


    /**
     * @param color 色值
     *              type  类型
     */
    private void showPopupWindow(int type, String color) {
        //设置contentView
        View contentView = null;
        if (type == 3) {
            contentView = LayoutInflater.from(this).inflate(R.layout.adapter_unionpay, null);
        } else {
            contentView = LayoutInflater.from(this).inflate(R.layout.adapter_item, null);
        }
        mPopWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //设置透明背景
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#00000000"));
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setBackgroundDrawable(dw);
        mPopWindow.setContentView(contentView);
        //修改背景颜色
        line_bk = (LinearLayout) contentView.findViewById(R.id.line_bk);
        GradientDrawable myGrad = (GradientDrawable) line_bk.getBackground();
        myGrad.setColor(Color.parseColor(color));

        if (type == 3) {
            real_q1 = (RelativeLayout) contentView.findViewById(R.id.real_q1);
            real_q2 = (RelativeLayout) contentView.findViewById(R.id.real_q2);
            real_q1.setOnClickListener(this);
            real_q2.setOnClickListener(this);
        } else {
            real_sao = (RelativeLayout) contentView.findViewById(R.id.real_sao);
            real_sao.setOnClickListener(this);
        }
        real_code = (RelativeLayout) contentView.findViewById(R.id.real_code);
        real_code.setOnClickListener(this);
        //显示PopupWindow
        backgroundAlpha(0.5f);
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_normal_key_board, null);
        //PopupWindow动画效果
        mPopWindow.setAnimationStyle(R.style.PopupAnimation);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
        //popu的监听
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    private void showMsg(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    /**
     * 关闭PopupWindow
     */
    private void hide() {
        if (mPopWindow != null && mPopWindow.isShowing()) {
            mPopWindow.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.real_q1:
                //快捷支付1
                channel_name = "YTZF";
                intent.setClass(QuickPayActivity.this, CardActivity.class);
                intent.putExtra("state", "2");
                intent.putExtra("channel_name", channel_name);
                startActivityForResult(intent, 1);
                break;
            case R.id.real_q2:
                //快捷支付2
                channel_name = "MLZF";
                intent.setClass(QuickPayActivity.this, CardActivity.class);
                intent.putExtra("state", "2");
                intent.putExtra("channel_name", channel_name);
                startActivityForResult(intent, 1);
                break;
            case R.id.real_sao:
                if (pay_type == 1) {
                    // showMsg("微信扫一扫");
                    busCode = "3205";
                    intent = new Intent(this, CaptureActivity.class);
                    intent.putExtra("busCode", busCode);
                    intent.putExtra("orderAmt", moneyS());
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                    break;
                } else if (pay_type == 2) {
                    //支付宝扫一扫
                    busCode = "3107";
                    intent = new Intent(this, CaptureActivity.class);
                    intent.putExtra("busCode", busCode);
                    intent.putExtra("orderAmt", moneyS());
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }
                break;
            case R.id.real_code:
                if (pay_type == 1) {
                    // showMsg("微信二维码");
                    busCode = "3101";
                    qrcode();
                } else if (pay_type == 2) {
                    // showMsg("支付宝二维码");
                    busCode = "3201";
                    qrcode();
                } else {
                    showMsg("正在开发中，敬请期待...");
                }
                break;
            case R.id.iv_back:
                finish();
                break;
        }
        hide();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    String card = data.getStringExtra("card_num");
                    submit(card);
                }
                break;
            case REQUEST_CODE_SCAN:
                if (resultCode == RESULT_OK) {
                    authCode = data.getStringExtra(DECODED_CONTENT_KEY);
                    busCode = data.getStringExtra("busCode");
                    money = data.getStringExtra("orderAmt");
                    qrcode();
                }
                break;
            case 3:
                if (resultCode == RESULT_OK) {
                    //入驻成功回到页面不做操作
                }
                break;
        }

    }

    /**
     * 两者区别在于是否有  authCode  参数
     * 二维码支付   主扫支付
     */
    public void qrcode() {
        map = new HashMap<String, String>();
        map.put("userId", AppConst.getUser().getId());
        map.put("orderAmt", moneyS());
        map.put("busCode", busCode);
        if (!authCode.equals("")) {
            map.put("authCode", authCode);
        }
        showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().path(this, handler, code_url, map, HttpCode.CODE_PAY);
    }


    /**
     * 商户是否入驻
     */
    private void isEnter() {
        map = new HashMap<String, String>();
        map.put("user_id", AppConst.getUser().getId());
        //showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().path(this, handler, isenter_url, map, HttpCode.IS_ENTER);
    }

    /**
     * 格式化后台需要的金额格式
     *
     * @return
     */
    private String moneyS() {
        //这么做是为了规避输入金额前面有0的情况，先转double，再转回String。
        money = Double.parseDouble(money) + "";
        String[] amounts = (money.replace(".", " ")).split(" ");
        if (amounts.length > 1) {
            if (amounts[1].length() == 1) {
                amounts[1] = amounts[1] + "0";
                money = amounts[0] + "." + amounts[1];
            }
            if (amounts[1].length() > 1) {
                amounts[1] = amounts[1].substring(0, 2);
                money = amounts[0] + "." + amounts[1];
            }
        } else {
            money = money + ".00";
        }
        return money;
    }

    /**
     * 银联快捷支付
     *
     * @param card
     */
    private void submit(String card) {
        map = new HashMap<String, String>();
        map.put("user_id", AppConst.getUser().getId());
        map.put("amount", moneyS());
        map.put("paybank", card);
        map.put("des", "");
        map.put("Channel_type", channel_name);
        showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().path(this, handler, cardUrl, map, HttpCode.QUICKPAY);
    }

    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (pd != null) {
                    pd.dismiss();
                }
                switch (msg.what) {
                    case HttpCode.networkabnormal:
                        showMsg("当前网络不可用");
                        break;
                    case HttpCode.http_failed:
                        showMsg("连接失败");
                        break;
                    case HttpCode.http_timeout:
                        showMsg("请求超时");
                        break;
                    case HttpCode.QUICKPAY:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                System.out.println("快捷支付" + json);
                                intent.putExtra("data", json.getString("data"));
                                intent.setClass(QuickPayActivity.this, QuickPayThreeActivity.class);
                                startActivity(intent);
                            } else {
                                showMsg("数据提交失败");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case HttpCode.IS_ENTER:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                //showMsg("商户已经入驻");
                                //判断金额
                                money = textAmount.getText().toString().trim();
                                if (money.equals("")) {
                                    money = "0";
                                }
                                double mf = Double.parseDouble(money);
                                if (mf > 0) {
                                    if (pay_type == 1) {
                                        //微信
                                        showPopupWindow(pay_type, "#009F45");
                                    } else if (pay_type == 2) {
                                        //支付宝
                                        showPopupWindow(pay_type, "#0089E1");
                                    }
                                } else {
                                    showMsg("请输入支付金额");
                                }
                            } else {
                                //商户未入住
                                intent.setClass(QuickPayActivity.this, ShoppingunitActivity.class);
                                startActivityForResult(intent, 3);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case HttpCode.CODE_PAY:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                if (authCode.equals("")) {
                                    String url = json.getJSONObject("data").getString("data");
                                    intent.setClass(QuickPayActivity.this, CodePayActivity.class);
                                    intent.putExtra("url", url);
                                    intent.putExtra("busCode", busCode);
                                    startActivity(intent);
                                } else {
                                    if (json.getJSONObject("data").getString("result").equals("SUCCESS")) {
                                        showMsg(json.getJSONObject("data").getString("msg"));
                                        finish();
                                    } else {
                                        showMsg(json.getJSONObject("data").getString("msg"));
                                    }
                                    showMsg("支付成功");
                                }
                            } else {
                                showMsg(json.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清空静态变量
        MainFragment.listA.clear();
    }
}
